package odgs.message.server;

import java.util.List;

import odgs.Connection;
import odgs.Contents;
import odgs.ContentsFile;
import odgs.Result;
import odgs.message.Message;
import odgs.message.MessageHandler;
import odgs.message.MessageProcessor;
import odgs.transaction.ContentsRemoveTransaction;

public class ContentsRemoveTransactionRequestHandler implements MessageHandler
{
	public void execute(MessageProcessor processor, Message msg, Connection con)
	{
		boolean canDelete = true;
		int result = 0;
		ContentsRemoveTransaction tran = (ContentsRemoveTransaction) msg.get("transaction");
		Contents cont = tran.getDest();
		
		if(processor.getServerManager().isLockContents(cont))
		{
			canDelete = false;
			result = Result.CONTENTS_IS_LOCK;
		}

		List<ContentsFile> files = processor.getServerManager().getContentsFile(cont);
		
		if(files.size() == 0)
		{
			canDelete = false;
			result = Result.CONTENTS_FILE_NOT_EXIST;
		}
		
		for (ContentsFile file : files)
		{
			if(!processor.getServerManager().isConnected(file.getNodeId()))
			{
				canDelete = false;
				result = Result.CONTENTS_USER_NOT_CONNECTED;
				break;
			}
		}
		
		if(canDelete)
		{
			for (ContentsFile file : files)
			{
				if(file != null)
				{
					if(processor.getServerManager().isConnected(file.getNodeId()))
					{
						String ip = processor.getServerManager().getIP(file.getNodeId());
						Connection deleteCon = processor.getNetworkManager().getConnection(ip);
						if(deleteCon != null)
						{
							Message deleteMsg = new Message();
							deleteMsg.setName(Message.FILE_DELETE_ORDER);
							deleteMsg.put("file", file);
							deleteMsg.put("transaction", tran);
							deleteMsg.put("ip", con.getIP());
							deleteCon.sendMessage(deleteMsg);
						}
					}
					else
					{
						
					}
				}
			}
		}
		else
		{
			Message reMsg = new Message();
			reMsg.setName(Message.CONTENTS_REMOVE_TRANSACTION_RESPONSE);
			reMsg.put("transaction", tran);
			reMsg.setResult(result);
			con.sendMessage(reMsg);
		}
	}
}